local skynet = require "skynet"
local socket = require "socket"
local httpd  = require "http.httpd"
local sockethelper = require "http.sockethelper"
local urllib  = require "http.url"
local cluster = require "cluster"

local table = table
local string = string

local listen_web_port = skynet.getenv "web_port"
local web_passwod     = skynet.getenv "web_passwd"

local centser = nil
local match_ser = nil
local mode = ...

if mode == "agent" then

local function requst_bypath(path, qt, method,body)

	if qt == nil  then
		return 500
	end

	local bSucceed = false
	if qt["passwd"] ~= nil then
		if qt["passwd"] == web_passwod then
			bSucceed = true
		end
	end

	if bSucceed == false then
		skynet.error("fail: passwd", qt["passwd"])
		return 501
	end

	-- if centser == nil then
		-- return 502
	-- end
   	
	skynet.error("requst method:",method)
	skynet.error("requst body:",body)

	if string.find(path,"broadcast") then

        skynet.send(".marquee","lua","RequireMarqueeMsg")
		return 200,nil

	elseif string.find(path,"match_get_match_json") then

		local str = match_ser.req.web_get_match_json(tonumber(qt["match_id"]))
		return 200,str

	elseif string.find(path,"match_get_defalut_match_json") then
		local str = match_ser.req.web_get_defalut_match_json(tonumber(qt["match_type"]))
		return 200,str

	elseif string.find(path,"match_contrl_match") then
		local str = match_ser.req.web_contrl_match(tonumber(qt["match_id"]),tonumber(qt["active_id"]))
		return 200,str

	elseif string.find(path,"match_commit_match_json") and  method == "POST" then
		local str = match_ser.req.web_commit_match_json(tonumber(qt["new"]),body)
		return 200,str

	elseif string.find(path,"match_get_match_list") then
		local str = match_ser.req.web_get_match_list()
		return 200,str

	elseif string.find(path,"match_get_select_def_list") then
		local str = match_ser.req.web_get_select_def()
		return 200,str
	end

	return 503
end

local function response(id, ...)
	local ok, err = httpd.write_response(sockethelper.writefunc(id), ...)
	if not ok then
		-- if err == sockethelper.socket_error , that means socket closed.
		skynet.error(string.format("fd = %d, %s", id, err))
	end
end

skynet.start(function()
	skynet.dispatch("lua", function (_,_,id)
		socket.start(id)
		-- limit request body size to 8192 (you can pass nil to unlimit)
		local code, url, method, header, body = httpd.read_request(sockethelper.readfunc(id), 8192)
		if code then
			if code ~= 200 then
				response(id, code)
			else

				local tmp = {}

				if header.host then
					--table.insert(tmp, string.format("host:%s", header.host))
				end

				for k,v in pairs(header) do
					table.insert(tmp, string.format("%s:%s",k,v))
				end
				table.insert(tmp, "\n")

				local path, query = urllib.parse(url)

				local qlist = nil
				if query then
					qlist = urllib.parse_query(query)
				end

				local ret, retstr = requst_bypath(path, qlist, method, body)

				if ret == 200 then
					table.insert(tmp, 1, "http/1.1 200 ok")
				else
					table.insert(tmp, 1, string.format("http/1.1 %d error ", ret))
				end

				table.insert(tmp,3, string.format("path:%s", path))

				if retstr then
					table.insert(tmp, retstr)
					table.insert(tmp, "\n")
				end
				
				response(id, ret, table.concat(tmp,"\n"))
			end
		else
			if url == sockethelper.socket_error then
				skynet.error("socket closed")
			else
				skynet.error(url)
			end
		end
		socket.close(id)
	end)

	--centser = cluster.snax("center", "centerser")
	match_ser = cluster.snax("center", "matchser")

end)

else

skynet.start(function()

	local agent = {}

	for i= 1, 2 do

		agent[i] = skynet.newservice(SERVICE_NAME, "agent")
	end

	local balance = 1

    
   	local id = socket.listen("0.0.0.0", listen_web_port)

	skynet.error("Listen web port "..listen_web_port)

	socket.start(id , function(id, addr)
		skynet.error(string.format("%s connected, pass it to agent :%08x", addr, agent[balance]))
		skynet.send(agent[balance], "lua", id)
		balance = balance + 1
		if balance > #agent then
			balance = 1
		end
	end)
	
end)

end
